package com.anket;


import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.application.NavigationHandler;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;



public class LoggedInCheck implements PhaseListener {

    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }

    public void beforePhase(PhaseEvent event) {
    	 System.out.println("before phase");
    	 
    	 
    	 FacesContext fc = event.getFacesContext();
         
         if (!loggedIn()) {
             NavigationHandler nh = fc.getApplication().getNavigationHandler();
             nh.handleNavigation(fc, "", "logout");
         }
         //redirect(fc, "/default.xhtml");
         
         
         
    }
    
    
    private static void redirect(FacesContext facesContext, String url) {
    	try {
    	facesContext.getExternalContext().redirect(url);
    	} catch (IOException e) {
    	throw new FacesException("Cannot redirect to " + url + " due to IO exception.", e);
    	}
    	}
    
    
    

    public void afterPhase(PhaseEvent event) {
    	
    	System.out.println("after phase");
    	
    	
        
    
    	
        
        
    }

    private boolean loggedIn() {
    	HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        String isLog = (String)session.getAttribute("isLoggedIn");
        System.out.println("isLoggedIn: " + isLog);
        return (isLog != null && isLog.equals("yes"));
    }
}